package com.testitems.service.interfaceDetection.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.testitems.Util.TestItemsUtils;
import com.testitems.common.web.result.Result;
import com.testitems.repo.entity.ExampleRecord;
import com.testitems.repo.mapper.ExampleRecordMapper;
import com.testitems.repo.request.SendRequest;
import com.testitems.repo.request.SingleInterfaceListReq;
import com.testitems.service.interfaceDetection.SingleInterfaceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

@Service
public class SingleInterfaceServiceImpl implements SingleInterfaceService {

    private final static Logger logger = LoggerFactory.getLogger(SingleInterfaceServiceImpl.class);
    // TODO 思路整理 : http请求，https请求，body类型，请求头信息，身份验证，是否做多接口组合访问

    @Autowired
    private ExampleRecordMapper exampleRecordMapper;

    /**
     * 发送请求
     * @param sendRequest
     * @return
     */
    @Override
    public Result sendRequest(SendRequest sendRequest) {
        Result result = new Result();
        // 暂时只支持http
        if (!"http".equals(sendRequest.getAgreement()) && !"https".equals(sendRequest.getAgreement()) ) {
            result.setCode(-1);
            result.setMessage("不支持当前协议，目前只支持http或Https");
            return result;
        } else {
            result = sendHttp(sendRequest);
        }


        return result;
    }

    /**
     * 发送http请求
     */
    private Result sendHttp(SendRequest sendRequest) {
        Result result = new Result();

        // 请求类型
        String type = sendRequest.getType().toUpperCase();
        // 请求方法
        String method = sendRequest.getMethod();
        // 请求地址
        String addr = sendRequest.getAddr();
        // 请求端口(可能为空)
        String port = "";

        if (sendRequest.getPort() != null) {
            port = sendRequest.getPort();
        }

        // 协议
        String agreement = sendRequest.getAgreement();
        // 参数
        String param = sendRequest.getParams().toJSONString();
        // 请求头
        JSONObject headers = sendRequest.getHeaders();

        String responce = "";
        HashMap<String, String> paramMap = new HashMap<>();
        String key = "";
        if (headers != null) {
            // 使用自定义请求头
            Iterator<String> iterator = headers.keySet().iterator();
            while (iterator.hasNext()) {
                key = iterator.next();
                paramMap.put(key,headers.getString(key));
            }

        } else if (TestItemsUtils.ThreadLocal.getJwtToken() != null) {
            // 默认使用jwtToken身份验证
            paramMap.put("jwtToken",TestItemsUtils.ThreadLocal.getJwtToken());

        } else {
            // 无特殊验证认证
        }
        String url = agreement + "://" + addr + ":" + port + method;
        switch (type) {
            case "GET" :
                // 协议
                responce = HttpRequest.get(url).body(param).headerMap(paramMap,false).execute().body();
                break;

            case "POST" :
                responce = HttpRequest.post(url).body(param).headerMap(paramMap,false).execute().body();
                break;

            default:
                logger.info("暂未添加其他协议");
                break;
        }

        logger.info(JSONObject.parseObject(responce).toJSONString());

        if (StringUtils.isNotBlank(responce)) {
            // 存在数据标记请求成功
            result.setSuccess(true);
            result.setCode(0);
            result.setMessage("请求成功");
            result.setData(JSONObject.parseObject(responce));
        } else {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("请求失败");
        }

        ExampleRecord exampleRecord = new ExampleRecord();
        exampleRecord.setResultCode(String.valueOf(result.getCode()));
        exampleRecord.setResultMessage(result.getMessage());
        exampleRecord.setRequestAddr(addr);
        exampleRecord.setRequestAgreement(agreement);
        exampleRecord.setRequestHeaders(paramMap.toString());
        exampleRecord.setRequestMethod(method);
        exampleRecord.setRequestParam(param.toString());
        exampleRecord.setRequestType(type);

        // TODO 记录请求结果
        exampleRecordMapper.addExampleRecord(exampleRecord);


        return result;
    }


    /**
     * 获取全部请求记录
     * @param singleInterfaceListReq
     * @return
     */
    @Override
    public Result singleInterfaceList(SingleInterfaceListReq singleInterfaceListReq) {
        Result result = new Result();
        List<ExampleRecord> exampleRecordList = exampleRecordMapper.selectExampleRecordList(singleInterfaceListReq);
        result.setData(exampleRecordList);

        return result;
    }
}
